package com.liupf.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.jfinal.util.PathUtil;
import com.mysql.jdbc.Statement;

public class SmsUtil {

	private static Log log = LogFactory.getLog(SmsUtil.class);

	private static Properties props = null;

	private static SmsClient smsClient = null;
	
	static{
		init();
	}
	
	public static void init() {
		ClassLoader cl = SmsUtil.class.getClassLoader();
		init(new File(cl.getResource("config.properties").getFile()));
	}

	public synchronized static void init(File configFile) {
	
		
		
		if(props == null) {
			props = new Properties();
	 		try {
				props.load(new FileReader(configFile));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if(smsClient == null) {
			try {
				smsClient = new SmsClient(props.getProperty("smsUser"), props.getProperty("smsPass"),props.getProperty("smsId"));
			} catch (UnsupportedEncodingException e) {
				log.error("初始化短信客户端失败", e);
			}
		}
	}

	public static void sendMessage(String phone, String message, String company) {
		if(props == null) {
			log.error("配置文件加载失败");
			return;
		}
		message += "【老兵镖局】";

		int mid = insertMessageIntoDB(phone, message, company);

		String msgId = null;
		if(mid > 0) {
			msgId = sendMessageToGateway(phone, message);
			updateMessageSentStatus(mid, msgId);
		}
	}

	private static void updateMessageSentStatus(int mid, String msgId) {
		Connection conn = getConn();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement("update sms_sent set msg_id = ?, status = 1 where id = ?");
			ps.setString(1, msgId);
			ps.setInt(2, mid);
			ps.executeUpdate();
		} catch (SQLException e) {
			log.error("更新短信状态失败， mid:" + mid + ", msgId:" + msgId, e);
		} finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	private static String sendMessageToGateway(String phone, String message) {
		if(smsClient == null) {
			log.error("短信服务初始化失败");
			return "0";
		}
		String msgId = smsClient.mt(phone, message, "", "", "");
		if(!msgId.startsWith("-")) {
			log.debug("短消息发送成功， phone:" + phone + ", message:" + message);
		} else {
			log.warn("短消息发送失败，返回码：" + msgId + ", phone:" + phone + ", message:" + message);
		}
		return msgId;
	}

	private static int insertMessageIntoDB(String phone, String message, String company) {
		Connection conn = getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		int mid = 0;
		try {
			ps = conn.prepareStatement("insert into sms_sent(phone, content, status, create_time) values(?, ?, ?, ?)"
					, Statement.RETURN_GENERATED_KEYS);
			ps.setString(1, phone);
			ps.setString(2, message);
			ps.setInt(3, 0);
			ps.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			if(rs.next()) 
				mid = rs.getInt(1);
			
			if(!(company == null || "".equals(company))){				
				ps = conn.prepareStatement("update tel_company set message_num = message_num-1 where company=? and message_num > 0");
				ps.setString(1, company);
				int cnt = ps.executeUpdate();
				if(cnt == 0){
					mid = 0;
				}else{
					String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
					ps = conn.prepareStatement(insertMessage);
					ps.setString(1, phone);
					ps.setString(2, message);
					ps.setString(3, company);
					ps.setDate(4, new java.sql.Date(Calendar.getInstance().getTime().getTime()));
					
					ps.executeUpdate();
				}
			}
		} catch (SQLException e) {
			log.error("记录短信失败， phone:" + phone + ", message:" + message, e);
		} finally {
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
				}
			}
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
				}
			}
		}
		return mid;
	}

	public static Connection getConn() {
        String driverClass = "com.mysql.jdbc.Driver";
        String url = props.getProperty("jdbcUrl");//
        String user = props.getProperty("user");;//MySQ帐号
        String password = props.getProperty("password");//MYSQL密码
        Connection conn = null;
        try {
            Class.forName(driverClass).newInstance();
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
        	log.error("获取数据库链接失败", e);
        }
        return conn;
    }

	//查得可用短信条数
	public static String getSmsBalanceToGateway() {
		if(smsClient == null) {
			File configFile = new File(PathUtil.getWebRootPath(),
					"/WEB-INF/config.properties");
			init(configFile);
		}

		if(smsClient == null) {
			log.error("短信服务初始化失败");
			return "-1";
		}
		String msgId = smsClient.getBalance();
		if(!msgId.startsWith("-")) {
			log.debug("可用短信条数 发送成功");
		} else {
			log.warn("短消息发送失败，返回码：" + msgId);
		}
		System.out.println("可用短信条数,返回码:  " + msgId);
		
		return msgId;
	}
	
	public static void sendPush(String title,String content,String registerId,String phoneType){
		try{
			String key = "938e5c69665bead3d5b4ba75";
			String pass = "31bd0ef3b2b86bbe9dfa03f9";
    		JPushClient jPushClient = new JPushClient(key, pass, 3);
    		PushPayload pushPayload = null;
    		if("IOS".equals(phoneType)){
    			pushPayload = buildPushObjectIos(new String[]{},title,content,registerId);
    		}else if("ANDROID".equals(phoneType)){
    			pushPayload = buildAndroidWinphonePayload(new String[]{},title,content,registerId);
    		}
    		System.out.println("pushPayload:"+pushPayload);
    		jPushClient.sendPush(pushPayload);
    	}catch(Exception e){
    		e.printStackTrace();
    		System.out.println(e);
    	}
	}

	private static PushPayload buildAndroidWinphonePayload(String[] alias,
    	    String alert,String title,String registerId) {
    	        return PushPayload.newBuilder()
    	                .setPlatform(Platform.all())
    	                .setAudience(Audience.registrationId(new String[]{registerId}))
    	                .setNotification(Notification.newBuilder()
    	                .setAlert(alert)
    	                .addPlatformNotification(AndroidNotification.newBuilder()
    	                .setTitle(title).build())
    	                .build())
    	                .build();
    }
	
	public static PushPayload buildPushObjectIos(String[] alias,
    	    String alert,String title,String registerId) {  
        return PushPayload.newBuilder()  
                .setPlatform(Platform.ios())  
                .setAudience(Audience.registrationId(new String[]{registerId}))  
                .setNotification(Notification.newBuilder()  
                        .setAlert(alert)  
                        //.addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).build())  
                        .addPlatformNotification(IosNotification.newBuilder().incrBadge(1).addExtra("extra_key", "extra_value").build())  
                        .build())  
                .build();  
    }
	
	public static void main(String[] args) {
		//sendMessage("13524555201", "hello");
	}
}
